package com.common;
import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.sql.Connection;

public class MysqlUtils {
    Connection mycon;
    public void createCon(String jdbc,String username,String password) throws ClassNotFoundException {
        try{
            Class.forName("com.mysql.cj.jdbc.Driver");
            mycon = DriverManager.getConnection(jdbc,username,password);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
            System.out.println("数据库配置连接失败");
        }
    }
    public boolean hasResult(String sql){
        try{
            Statement statement=mycon.createStatement();
            ResultSet resultSet=statement.executeQuery(sql);
            if(resultSet.next()){
                return true;
            }
            return false;
        } catch (SQLException throwables) {
            throwables.printStackTrace();
            System.out.println("查询操作失败");
            return false;
        }
    }
    public List<Map<String,String>> queryResult(String sql){
        try{
            Statement statement=mycon.createStatement();
            ResultSet resultSet=statement.executeQuery(sql);
            List<Map<String,String>> datalist=new ArrayList<>();
            while (resultSet.next()){
                Map<String,String> lineData=new HashMap<>();
                for(int i=1;i <=resultSet.getMetaData().getColumnCount();i++){
                    lineData.put(resultSet.getMetaData().getColumnName(i),resultSet.getString(i));
                }
                datalist.add(lineData);
            }
            return datalist;
        } catch (SQLException throwables) {
            throwables.printStackTrace();
            return new ArrayList<>();
        }
    }
}
